import os
import uuid

from module import fileutils, inodeutils

dirname, filename = os.path.split(os.path.abspath(__file__)) 
# os.path.realpath(__file__)

SAVE_INODE_PATH = os.path.join(dirname, 'temp')

BUCKET_BASE_PATH = os.path.join(dirname, 'bucket_data')

DEFALUT_BUCKET_NAME = 'default'

SYSTEM_BUCKET_NAME = 'system'

def init():
    if os.path.exists(SAVE_INODE_PATH) == False:
        os.makedirs(SAVE_INODE_PATH)

    fileutils.emptyFolder(SAVE_INODE_PATH, ['.gitkeep'])

    filepath = os.path.join(BUCKET_BASE_PATH, DEFALUT_BUCKET_NAME)
    files = fileutils.listAllFile(filepath, ['.gitkeep'])
    for itemPath in files:
        absolutePath = itemPath
        itemPath = itemPath.replace(filepath, '')
        itemPath = itemPath.replace('\\', '/')
        itemPath = itemPath[1:]

        inodeutils.saveInode(DEFALUT_BUCKET_NAME, absolutePath, itemPath, SAVE_INODE_PATH)

def listInodeName():
    files = os.listdir(SAVE_INODE_PATH)
    result = []

    for fi in files:
        fi_d = os.path.join(SAVE_INODE_PATH, fi)
        if os.path.isfile(fi_d):
            result.append(fi)

    return result

def queryInode(inodeName):
    inodePath = os.path.join(SAVE_INODE_PATH, inodeName)

    if os.path.exists(inodePath) and os.path.isfile(inodePath):
        fd = open(inodePath, mode="r", encoding="utf-8")
        info = fd.read()
        fd.close()
        return info

    return ''

def queryFile(bucket, relativePath):
    filepath = os.path.join(BUCKET_BASE_PATH, bucket, relativePath)
    fd = open(filepath, mode="rb")
    binary = fd.read()
    fd.close()
    return binary

def addFile(bucket, fileName, fileBtye):
    bucketPath = os.path.join(BUCKET_BASE_PATH, bucket)
    if os.path.exists(os.path.join(bucketPath, fileName)) == False:
        os.makedirs(os.path.join(bucketPath, fileName))

    filesize = len(fileBtye)
    uuuid = str(uuid.uuid1()).replace('-', '')
    relativePath = os.path.join(fileName, uuuid)

    filepath = os.path.join(bucketPath, relativePath)

    fd = open(filepath, mode="wb")
    fd.write(fileBtye)
    fd.close()

    return inodeutils.generateInode(bucket, relativePath, fileName, filesize)
